<template>
    <div>
        
        <el-card class="personcenter" shadow="hover">
            <el-row type="flex" justify="end">
                <el-button type="primary" @click="verificationVisble = true">密码重置</el-button>
                <el-button type="primary" @click ="resetPhone">修改电话</el-button>
                <el-button type="primary" @click="resetEmail">修改邮箱</el-button>
            </el-row>
            <el-descriptions class="personcenterDescrib" title="个人信息展示" direction="vertical" :column="4"  border>
                
                <el-descriptions-item   label="用户名">{{PersonData.userName}}</el-descriptions-item>
                <el-descriptions-item  label="手机号">{{PersonData.userPhone}}</el-descriptions-item>
                <el-descriptions-item  label="身份证" :span="2">{{PersonData.userId}}</el-descriptions-item>
                <el-descriptions-item  label="性别">
                    <el-tag size="small" v-if="PersonData.userGender==0">女</el-tag>
                    <el-tag size="small" v-if="PersonData.userGender==1">男</el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="年龄">{{PersonData.userAge}}</el-descriptions-item>
                
                <el-descriptions-item label="邮件">{{PersonData.userEmail}}</el-descriptions-item>
                <el-descriptions-item label="密码">{{PersonData.userPassword}}</el-descriptions-item>
                <el-descriptions-item label="生日">{{PersonData.userBirth}}</el-descriptions-item>
                <el-descriptions-item v-if="authes[PersonData.userAuth-1]&&authes"
                    label="权限">{{authes[PersonData.userAuth-1].authDesc}}</el-descriptions-item>
                <el-descriptions-item v-if="haveclass && classes[PersonData.userClass-1]" label="类别">{{classes[PersonData.userClass-1].className}}</el-descriptions-item>
            </el-descriptions>
        </el-card>
        <el-dialog title="验证" :visible.sync="verificationVisble" >
            <el-form :model="verificationData"  :rules="rules" ref="verificationData">
                <el-form-item label="手机号" prop="phone" ref="phone">
                    <el-input v-model="verificationData.phone" placeholder="请输入手机号">
                        <el-select placeholder="+86"></el-select>
                    </el-input>
                </el-form-item>
                <el-form-item label="验证码" prop="verificationCode">
                    <el-input v-model="verificationData.verificationCode" placeholder="请输入验证码">
                        <el-button slot="suffix" :disabled="disabled" @click="getCode">
                            <span class="Time">{{btnTxt}}</span>
                        </el-button>
                    </el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="verificationVisble = false">取 消</el-button>
                <el-button type="primary" @click="submitVerification">确 定</el-button>
            </div>
        </el-dialog>
        <el-dialog title="重置密码" :visible.sync="resetPasswordVisible">
            <el-form :model="resetPasswordData" status-icon :rules="resetPasswordrules" ref="resetPasswordData" label-width="100px" class="demo-ruleForm">
                <el-form-item label="密码" prop="pass">
                    <el-input type="password" v-model="resetPasswordData.pass" autocomplete="off" ></el-input>
                </el-form-item>
                <el-form-item label="确认密码" prop="checkPass">
                    <el-input type="password" v-model="resetPasswordData.checkPass" autocomplete="off" ></el-input>
                </el-form-item>
                
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="resetPasswordVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitresetPassword">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
    export default {
            data() {
                 var validatePass = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请输入密码'));
                } else {
                    if (this.resetPasswordData.checkPass !== '') {
                        this.$refs.resetPasswordData.validateField('checkPass');
                    }
                    callback();
                }
            };
            var validatePass2 = (rule, value, callback) => {
                if (value === '') {
                    callback(new Error('请再次输入密码'));
                } else if (value !== this.resetPasswordData.pass) {
                    callback(new Error('两次输入密码不一致!'));
                } else {
                    callback();
                }
            };
                return {
                     btnTxt: "获取验证码",
                    // 是否禁用  即点击之后一段时间内无法再点击
                    disabled: false,
                    time: 0,
                    verificationVisble:false,
                    resetPasswordVisible:false,
                    role:null,
                    haveclass:true,
                    PersonData:{
                        userId: '',
                        userName: '',
                        userAge: '',
                        userGender: '',
                        userPassword: '',
                        userEmail: '',
                        userPhone: '',
                        userClass: '',
                        userAuth:'',
                        userBirth: ''    
                    },
                    verificationData:{
                        phone:'',
                        role:'',
                        verificationCode:''
                    },
                    resetPasswordData:{
                        pass:'',
                        checkPass:'',
                    },
                    authes:[],
                    classes:[],
                    rules: {
                        phone: [
                            { required: true, trigger: 'blur', message: '请输入11位手机号' },
                            { required: true, trigger: 'blur', min: 11, max: 11, message: '长度不符合' },
                            
                        ],
                        verificationCode: [
                            { required: true, trigger: 'blur', message: '请输入4位验证码' },
                            { required: true, trigger: 'blur', min: 4, max: 6, message: '验证码错误' }
                        ],
                    },
                    resetPasswordrules: {
                        pass: [
                            { required: true, trigger: 'blur', message: '请输入密码' },
                            { validator: validatePass, trigger: 'blur' }
                        ],
                        checkPass: [
                            { required: true, trigger: 'blur', message: '确认密码' },
                            { validator: validatePass2, trigger: 'blur' }
                        ],
                        
                    }
                };
            },
            methods: {
                async fetchData(){
                    this.role = this.$store.state.userdata.roleName;
                    var userId = this.$store.state.userdata.userId;
                    this.$axios({
                        method: 'get',
                        url: 'http://localhost:8080/class',
                    }).then(res => {
                        if (res.data.code == 1) {
                            this.classes = res.data.data;
                        }

                    })
                    this.$axios({
                        method: 'get',
                        url: 'http://localhost:8080/auth/all',
                    }).then(res => {
                        if (res.data.code == 1) {
                            this.authes = res.data.data;
                        }

                    })
                    
                    if(this.role==='professor'){
                        this.$axios({
                            method:'get',
                            url: "http://localhost:8080/professors/findById",
                            params:{
                                userId:userId
                            }
                        }).then(res=>{
                            if(res.data.code==1){
                                this.PersonData.userName = res.data.data.proName;
                                this.PersonData.userId = res.data.data.proId;
                                this.PersonData.userGender = res.data.data.proGender;
                                this.PersonData.userAge =  res.data.data.proAge;
                                this.PersonData.userEmail = res.data.data.proEmail;
                                this.PersonData.userPassword = res.data.data.proPassword;
                                this.PersonData.userPhone = res.data.data.proPhone;
                                this.PersonData.userAuth = res.data.data.proAuth;
                                this.PersonData.userClass = res.data.data.proClass;
                                this.PersonData.userBirth = res.data.data.proBirth;
                            }
                        })
                    }else if(this.role==='contestant'){
                        this.$axios({
                            method: 'get',
                            url: "http://localhost:8080/contestants/findById",
                            params: {
                                userId: userId
                            }
                        }).then(res => {
                            if (res.data.code == 1) {
                                this.PersonData.userName =      res.data.data.conName;
                                this.PersonData.userId =        res.data.data.conId;
                                this.PersonData.userGender =    res.data.data.conGender;
                                this.PersonData.userAge =       res.data.data.conAge;
                                this.PersonData.userEmail =     res.data.data.conEmail;
                                this.PersonData.userPassword =  res.data.data.conPassword;
                                this.PersonData.userPhone =     res.data.data.conPhone;
                                this.PersonData.userClass =     res.data.data.conClass;
                                this.PersonData.userAuth = 5;
                                this.PersonData.userBirth =     res.data.data.conBirth;
                            }
                            console.log(this.PersonData);
                        })
                    }else{
                        this.haveclass = false;
                        this.$axios({
                            method: 'get',
                            url: "http://localhost:8080/administors/findById",
                            params: {
                                userId: userId
                            }
                        }).then(res => {
                            if (res.data.code == 1) {
                                this.PersonData.userName =      res.data.data.admName;
                                this.PersonData.userId =        res.data.data.admId;
                                this.PersonData.userGender =    res.data.data.admGender;
                                this.PersonData.userAge =       res.data.data.admAge;
                                this.PersonData.userEmail =     res.data.data.admEmail;
                                this.PersonData.userPassword =  res.data.data.admPassword;
                                this.PersonData.userPhone =     res.data.data.admPhone;
                                this.PersonData.userClass =     res.data.data.admClass;
                                this.PersonData.userAuth = 1;
                                this.PersonData.userBirth =     res.data.data.admBirth;
                            }
                            
                        })
                    }
                },
                submitresetPassword(){
                    this.$refs.resetPasswordData.validate((valid) => {
                        if (valid) {
                            console.log("submitresetPassword:"+this.$store.state.userdata.roleName);
                            if (this.$store.state.userdata.roleName === 'admin') {
                                this.$axios({
                                    method:'post',
                                    url: "http://localhost:8080/administors/PersonCenter_upload",
                                    data: {
                                        id: this.$store.state.userdata.userId,
                                        newPassword: this.resetPasswordData.pass,
                                        phone: '',
                                        email: ''
                                    },
                                    headers: {
                                        'Content-Type': 'multipart/form-data'
                                    }
                                }).then(res=>{
                                    if(res.data.code===1){
                                        this.resetPasswordVisible = false;
                                        this.$message.success("更新密码成功");
                                        this.fetchData();
                                    }else{
                                        this.$message.error("更新密码失败");
                                    }
                                })
                            }
                            if (this.$store.state.userdata.roleName === 'contestant') {
                                this.$axios({
                                    method: 'post',
                                    url: "http://localhost:8080/contestants/PersonCenter_upload",
                                    data: {
                                        id: this.$store.state.userdata.userId,
                                        newPassword: this.resetPasswordData.pass,
                                        phone: '',
                                        email: ''
                                    },
                                    headers: {
                                        'Content-Type': 'multipart/form-data'
                                    }
                                }).then(res => {
                                    if (res.data.code === 1) {
                                        this.$message.success("更新密码成功");
                                        this.resetPasswordVisible = false;
                                        this.fetchData();
                                    } else {
                                        this.$message.error("更新密码失败");
                                    }
                                })
                            }
                            if (this.$store.state.userdata.roleName === 'professor') {
                               this.$axios({
                                    method: 'post',
                                    url: "http://localhost:8080/professors/PersonCenter_upload",
                                    data: {
                                        id: this.$store.state.userdata.userId,
                                        newPassword: this.resetPasswordData.pass,
                                        phone :'',
                                        email :''
                                    },
                                   headers: {
                                       'Content-Type': 'multipart/form-data'
                                   }
                                }).then(res => {
                                    if (res.data.code === 1) {
                                        this.$message.success("更新密码成功");
                                        this.resetPasswordVisible = false;
                                        this.fetchData();
                                    } else {
                                        this.$message.error("更新密码失败");
                                    }
                                })
                            }
                        }
                    })
                },
                resetPhone(){
                    this.$prompt('请输入手机号', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        inputPattern: /1[35789]\d{9}/,
                        inputErrorMessage: '电话格式不正确'
                    }).then(({ value,action }) => {
                        if(action ==='confirm'){
                            if (this.$store.state.userdata.roleName === 'admin') {
                                this.$axios({
                                    method: 'post',
                                    url: "http://localhost:8080/administors/PersonCenter_upload",
                                    data: {
                                        id: this.$store.state.userdata.userId,
                                        newPassword: '',
                                        phone: value,
                                        email: ''
                                    },
                                    headers: {
                                        'Content-Type': 'multipart/form-data'
                                    }
                                }).then(res => {
                                    if (res.data.code === 1) {
                                        this.resetPasswordVisible = false;
                                        this.$message.success("更新手机号码成功");
                                        this.fetchData();
                                    } else {
                                        this.$message.error("更新手机号码失败");
                                    }
                                })
                            }
                            if (this.$store.state.userdata.roleName === 'contestant') {
                                this.$axios({
                                    method: 'post',
                                    url: "http://localhost:8080/contestants/PersonCenter_upload",
                                    data: {
                                        id: this.$store.state.userdata.userId,
                                        newPassword: '',
                                        phone: value,
                                        email: ''
                                    },
                                    headers: {
                                        'Content-Type': 'multipart/form-data'
                                    }
                                }).then(res => {
                                    if (res.data.code === 1) {
                                        
                                        this.resetPasswordVisible = false;
                                        this.$message.success("更新手机号码成功");
                                        this.fetchData();
                                    } else {
                                        this.$message.error("更新手机号码失败");
                                    }
                                })
                            }
                            if (this.$store.state.userdata.roleName === 'professor') {
                                this.$axios({
                                    method: 'post',
                                    url: "http://localhost:8080/professors/PersonCenter_upload",
                                    data: {
                                        id: this.$store.state.userdata.userId,
                                        newPassword: '',
                                        phone: value,
                                        email: ''
                                    },
                                    headers: {
                                        'Content-Type': 'multipart/form-data'
                                    }
                                }).then(res => {
                                    if (res.data.code === 1) {
                                        this.$message.success("更新电话号码成功");
                                        this.resetPasswordVisible = false;
                                        this.fetchData();
                                    } else {
                                        this.$message.error("更新电话号码失败");
                                    }
                                })
                            }
                        }
                    }).catch(() => {
                        this.$message({
                            type: 'info',
                            message: '取消输入'
                        });
                    });
                },
                 resetEmail() {
                    this.$prompt('请输入邮箱', '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        inputPattern: /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/,
                        inputErrorMessage: '邮箱格式不正确'
                    }).then(({ value,action }) => {
                       if (action === 'confirm') {
                            if (this.$store.state.userdata.roleName === 'admin') {
                                this.$axios({
                                    method: 'post',
                                    url: "http://localhost:8080/administors/PersonCenter_upload",
                                    data: {
                                        id: this.$store.state.userdata.userId,
                                        newPassword: '',
                                        phone: '',
                                        email: value
                                    },
                                    headers: {
                                        'Content-Type': 'multipart/form-data'
                                    }
                                }).then(res => {
                                    if (res.data.code === 1) {
                                        this.resetPasswordVisible = false;
                                        this.$message.success("更新邮箱成功");
                                        this.fetchData();
                                    } else {
                                        this.$message.error("更新邮箱失败");
                                    }
                                })
                            }
                            if (this.$store.state.userdata.roleName === 'contestant') {
                                this.$axios({
                                    method: 'post',
                                    url: "http://localhost:8080/contestants/PersonCenter_upload",
                                    data: {
                                        id: this.$store.state.userdata.userId,
                                        newPassword: '',
                                        phone: '',
                                        email: value
                                    },
                                    headers: {
                                        'Content-Type': 'multipart/form-data'
                                    }
                                }).then(res => {
                                    if (res.data.code === 1) {
                                        this.$message.success("更新邮箱成功");
                                        this.resetPasswordVisible = false;
                                        this.fetchData();
                                    } else {
                                        this.$message.error("更新邮箱失败");
                                    }
                                })
                            }
                            if (this.$store.state.userdata.roleName === 'professor') {
                                this.$axios({
                                    method: 'post',
                                    url: "http://localhost:8080/professors/PersonCenter_upload",
                                    data: {
                                        id: this.$store.state.userdata.userId,
                                        newPassword: '',
                                        phone: '',
                                        email: value
                                    },
                                    headers: {
                                        'Content-Type': 'multipart/form-data'
                                    }
                                }).then(res => {
                                    if (res.data.code === 1) {
                                        this.$message.success("更新邮箱成功");
                                        this.resetPasswordVisible = false;
                                        this.fetchData();
                                    } else {
                                        this.$message.error("更新邮箱失败");
                                    }
                                })
                            }
                        }
                    }).catch(() => {
                        this.$message({
                            type: 'info',
                            message: '取消输入'
                        });
                    });
                },
                submitVerification(){
                    
                    if (this.$store.state.userdata.roleName === 'admin') {
                        this.verificationData.role = 'administor'
                    }
                    if (this.$store.state.userdata.roleName === 'contestant') {
                        this.verificationData.role = 'contestant'
                    }
                    if (this.$store.state.userdata.roleName === 'professor') {
                        this.verificationData.role = 'professor'
                    }
                    
                    this.$refs.verificationData.validate((valid) => {
                        
                        if (valid) {
                            console.log("valid"+this.$store.state.userdata.roleName)
                            this.$axios({
                                method: 'post',
                                url: "http://localhost:8080/verification",
                                data: this.verificationData,
                                headers: {
                                    'Content-Type': 'multipart/form-data'
                                }
                            }).then(res => {
                                if (res.data.code == 1) {
                                    this.verificationVisble = false;
                                    this.resetPasswordVisible = true;
                                } else {
                                    this.$message({
                                        message: '验证失败',
                                        type: 'warning',
                                    })
                                }
                            })
                        }
                    })
                },
                //获取手机验证码方法
                getCode() {
                    // 校验手机号码
                    if (!this.verificationData.phone) {
                        //号码校验不通过
                        this.$message({
                            message: '请输入手机号',
                            type: 'warning',
                        });
                        //正则判断 从1开始，第二位是35789中的任意一位，以9数字结尾
                    } else if (!/1[35789]\d{9}/.test(this.verificationData.phone)) {
                        // 失去焦点后自动触发校验手机号规则
                    } else {
                        this.time = 60;
                        this.disabled = true;
                        //调用倒计时方法
                        this.timer();
                        // 封装的axios接口
                        this.$axios({
                            method: 'post',
                            url: 'http://localhost:8080/sendMsg',
                            data: {
                                phone: this.verificationData.phone
                            },
                            headers: {
                                'Content-Type': 'multipart/form-data'
                            }
                        }).then(res => {
                            if (res.data.code) {
                                this.$message({
                                    type: "success",
                                    message: '验证码已发送'
                                })
                            } else {
                                if (res.data.msg === '号码未注册') {
                                    this.$message({
                                        type: "error",
                                        message: '号码未注册'
                                    })
                                } else {
                                    this.$message({
                                        type: "error",
                                        message: '验证码发送失败'
                                    })
                                }

                            }
                        })
                    }
                },
                // 倒计时方法
                timer() {
                    if (this.time > 0) {
                        this.time--;
                        // console.log(this.time);
                        this.btnTxt = this.time + "s后重新获取验证码";
                        setTimeout(this.timer, 1000);
                    } else {
                        this.time = 0;
                        this.btnTxt = "获取验证码";
                        this.disabled = false;
                    }
                },
            },
            mounted() {
                this.fetchData();

            },
        }
</script>